﻿/*
创建人：Wangjh
日期：2022-04-28
描述：无限排产js
*/
var page = {
    pagetotal: 0,
    pageSize: 50,
    pageNumber: 1,
    rootPath: getRootPath(), //网站根路径
    ajaxUrl: getRootPath() + "/Ashx/ApsHandler/ApsInfiniteCapacity.ashx",
    //初始化页面
    init: function () {
        page.bind();
        customizedEasyuiPagination('pp'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        //主查询结果加载
        $("#gdContainerInfo").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                customizedEasyuiPagination('pp'); //定制化分页

            },
            onCheck: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();
            },
            onUncheck: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();

            },
            onCheckAll: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();
            },
            onUncheckAll: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();

            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 120 },
		         { field: 'CONTAINERNAME', title: '批次', width: 150 },
		         { field: 'PRODUCTDESC', title: '零件名称', width: 130 },
                 { field: 'QTY', title: '在制数', width: 60 },
                 { field: 'WORKFLOWINFO', title: '工艺信息', width: 180 },
                 { field: 'WORKFLOWSTEPNAME', title: '当前工序', width: 180 },
                 { field: 'CONTAINERTYPENAME', title: '流水卡类型', width: 100 },
                 { field: 'REALSTARTDATE', title: '批次实际开始日期', width: 120, formatter: function (value, row, index) {
                     if (value != null)
                         return dayjs(value).format("YYYY-MM-DD");
                 }
                 },
                 { field: 'MFGSTARTDDATE', title: '订单开始日期', width: 100 },
                 { field: 'MFGENDDDATE', title: '订单结束日期', width: 100 },
		         { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
		         { field: 'WORKFLOWID', title: '工艺', hidden: true },
                 { field: 'TOGETHERFLAG', title: '批次顺序', hidden: true },
                 { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
                 { field: 'CONTAINERTYPE', title: '流水卡类型', hidden: true },
                 { field: 'PRODUCTID', title: '零件图号ID', hidden: true },
                 { field: 'PRODUCTNAME', title: '零件图号', hidden: true },
                 { field: 'PRODUCTREVISION', title: 'PRODUCTREVISION', hidden: true },
                 { field: 'WORKFLOWNAME', title: 'WORKFLOWNAME', hidden: true },
                 { field: 'WORKFLOWREVISION', title: 'WORKFLOWREVISION', hidden: true }

	           ]]
        });
        //正排
        $("#gdPositiveInfo").datagrid({
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 120 },
		         { field: 'CONTAINERNAME', title: '批次', width: 150 },
		         { field: 'PRODUCTDESC', title: '零件名称', width: 130, hidden: true },
                 { field: 'QTY', title: '在制数', width: 60 },
                 { field: 'WORKFLOWINFO', title: '工艺信息', width: 180, hidden: true },
                 { field: 'STARTTIME', title: '开始时间', width: 125, formatter: function (value, row, index) {
                     if (value != null)
                         return value.substring(0, value.lastIndexOf(":"));
                 }
                 },
                 { field: 'ENDTIME', title: '结束时间', width: 125, formatter: function (value, row, index) {
                     if (value != null)
                         return value.substring(0, value.lastIndexOf(":"));
                 }
                 },
                 { field: 'OPERATE', title: '操作', width: 100, formatter: function (value, row, index) {
                     return "<button style='cursor:pointer' class='' onclick=page.viewGanttAndSave('[" + JSON.stringify({ apsPlanInfoID: row.APSPLANINFOID == null ? '' : row.APSPLANINFOID }) + "]') style='width: 60px; height: 22px'>查看</button>";
                 }
                 },
		         { field: 'WORKFLOWID', title: '工艺', hidden: true },
                 { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
                 { field: 'CONTAINERTYPE', title: '流水卡类型', hidden: true },
                 { field: 'PRODUCTREVISION', title: 'PRODUCTREVISION', hidden: true },
                 { field: 'WORKFLOWNAME', title: 'WORKFLOWNAME', hidden: true },
                 { field: 'WORKFLOWREVISION', title: 'WORKFLOWREVISION', hidden: true },
                 { field: 'APSPLANINFOID', title: 'APSPLANINFOID', hidden: true }

	           ]],
            rowStyler: function (index, row) {
                if (row.ENDTIME != null && dayjs(dayjs(row.ENDTIME).format('YYYY-MM-DD')) > dayjs(dayjs(row.MFGENDDDATE).format('YYYY-MM-DD'))) {
                    return 'background-color:#ffee00;';
                }
            }
        });
        //倒排
        $("#gdReverseInfo").datagrid({
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 120 },
		         { field: 'CONTAINERNAME', title: '批次', width: 150 },
		         { field: 'PRODUCTDESC', title: '零件名称', width: 130, hidden: true },
                 { field: 'QTY', title: '在制数', width: 60 },
                 { field: 'WORKFLOWINFO', title: '工艺信息', width: 180, hidden: true },
                 { field: 'STARTTIME', title: '开始时间', width: 125, formatter: function (value, row, index) {
                     if (value != null)
                         return value.substring(0, value.lastIndexOf(":"));
                 }
                 },
                 { field: 'ENDTIME', title: '结束时间', width: 125, formatter: function (value, row, index) {
                     if (value != null)
                         return value.substring(0, value.lastIndexOf(":"));
                 }
                 },
                 { field: 'OPERATE', title: '操作', width: 100, formatter: function (value, row, index) {
                     return "<button style='cursor:pointer' class='' onclick=page.viewGanttAndSave('[" + JSON.stringify({ apsPlanInfoID: row.APSPLANINFOID == null ? '' : row.APSPLANINFOID }) + "]') style='width: 60px; height: 22px'>查看</button>";
                 }
                 },
		         { field: 'WORKFLOWID', title: '工艺', hidden: true },
                 { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
                 { field: 'CONTAINERTYPE', title: '流水卡类型', hidden: true },
                 { field: 'PRODUCTREVISION', title: 'PRODUCTREVISION', hidden: true },
                 { field: 'WORKFLOWNAME', title: 'WORKFLOWNAME', hidden: true },
                 { field: 'WORKFLOWREVISION', title: 'WORKFLOWREVISION', hidden: true },
                 { field: 'APSPLANINFOID', title: 'APSPLANINFOID', hidden: true }

	           ]],
            rowStyler: function (index, row) {
                if (row.ENDTIME != null && dayjs(dayjs(row.ENDTIME).format('YYYY-MM-DD')) > dayjs(dayjs(row.MFGENDDDATE).format('YYYY-MM-DD'))) {
                    return 'background-color:#ffee00;';
                }
            }
        });

        //查询按钮
        $('#btnSearch').on("click", function () {
            page.pageNumber = 1;
            page.searchData();
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.searchData();
        });
        //移入批次按钮
        $('#btnAddPool').on("click", function () {
            page.addApsPool();
        });
        //移出批次按钮
        $('#btnRemoveApsPool').on("click", function () {
            page.removeApsPool();
        });
        //导出超期数据 add by zhangrj 20250915
        $('#btnExportOverTime').on("click", function () {
            var param = {
                action: "ExportOverTimeApsData",
                containerName: $("#txtContainer").textbox('getValue'),
                mfgorderName: $("#txtMfgorderName").textbox('getValue'),
                productName: $("#txtProduct").textbox('getValue'),
                factoryId: $("#factoryID").combobox('getValue'),
                orderStartDate: $("#txtOrderStartDate").datebox('getValue'),
                orderEndDate: $("#txtOrderEndDate").datebox('getValue')
            };
            FileDownLoad(page.ajaxUrl, param);
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true, true);
            page.pageNumber = 1; page.pagetotal = 0
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });

        //正排计算
        $('#btnPositive').on("click", function () {
            page.positiveCalculate();
        });
        //正排甘特图查看
        $('#btnPositiveGantt').on("click", function () {
            clearMessage();
            var checkDatas = $("#gdPositiveInfo").datagrid("getChecked");
            if (checkDatas.length == 0) {
                displayMessage("请勾选排产记录", false);
                return;
            }
            var popData = [];
            checkDatas.forEach(function (item) {
                popData.push({
                    apsPlanInfoID: item.APSPLANINFOID
                });
            });
            page.viewGanttAndSave(JSON.stringify(popData));
        });
        //倒排甘特图查看
        $('#btnReverseGantt').on("click", function () {
            clearMessage();
            var checkDatas = $("#gdReverseInfo").datagrid("getChecked");
            if (checkDatas.length == 0) {
                displayMessage("请勾选排产记录", false);
                return;
            }
            var popData = [];
            checkDatas.forEach(function (item) {
                popData.push({
                    apsPlanInfoID: item.APSPLANINFOID == null ? '' : item.APSPLANINFOID
                });
            });
            page.viewGanttAndSave(JSON.stringify(popData));
        });
        //倒排计算
        $('#btnReverse').on("click", function () {
            page.ReverseCalculate();
        });
        page.LoadFactory();
    },
    //分厂下拉初始化
    LoadFactory: function () {
        $.ajax({
            type: "Post",
            url: getRootPath() + "/Ashx/CommonHandler.ashx?action=getFactory",
            data: {},
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#factoryID').combobox({
                    data: result,
                    valueField: 'FACTORYID',
                    textField: 'FACTORYNAME',
                    value: result[0].FACTORYID //默认值
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //倒排计算
    ReverseCalculate: function () {
        var checkedData = $("#gdReverseInfo").datagrid("getChecked");
        var gridID = "#gdReverseInfo";
        var reuqestData = [];
        reuqestData = checkedData.map(function (item) {
            return {
                CONTAINERID: item.CONTAINERID,
                QTY: item.QTY,
                WORKFLOWID: item.WORKFLOWID,
                ENDTIME: item.MFGENDDDATE
            }
        });
        //console.log(reuqestData);
        var param = {
            action: "reverseCalculate",
            containers: JSON.stringify(reuqestData)
        };
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ApsHandler/ApsInfiniteCapacity.ashx",
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    var returnData = page.generateInfiniteApsData(checkedData, result.ReturnData);
                    console.log(returnData);
                    $(gridID).datagrid('loadData', { total: returnData.length, rows: returnData });
                    $(gridID).datagrid('checkAll');

                    displayMessage("倒排成功", true);
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    }
    //正排计算
    , positiveCalculate: function () {
        var checkedData = $("#gdPositiveInfo").datagrid("getChecked");
        var gridID = "#gdPositiveInfo";
        var reuqestData = [];
        reuqestData = checkedData.map(function (item) {
            return {
                CONTAINERID: item.CONTAINERID,
                QTY: item.QTY,
                WORKFLOWID: item.WORKFLOWID,
                STARTTIME: item.REALSTARTDATE
            }
        });
        //console.log(reuqestData);
        var param = {
            action: "positiveCalculate",
            containers: JSON.stringify(reuqestData)
        };
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ApsHandler/ApsInfiniteCapacity.ashx",
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    var returnData = page.generateInfiniteApsData(checkedData, result.ReturnData);
                    //console.log(returnData);
                    $("#gdPositiveInfo").datagrid('loadData', { total: returnData.length, rows: returnData });
                    $("#gdPositiveInfo").datagrid('checkAll');

                    displayMessage("正排成功", true);
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });

    },
    //正排，倒排数据生成
    generateInfiniteApsData: function (containerData, apsData) {
        //正排信息
        var result = [];
        containerData.forEach(function (item) {
            var _item = {
                MFGORDERNAME: item.MFGORDERNAME,
                CONTAINERID: item.CONTAINERID,
                CONTAINERNAME: item.CONTAINERNAME,
                PRODUCTDESC: item.PRODUCTDESC,
                PRODUCTREVISION: item.PRODUCTREVISION,
                QTY: item.QTY,
                WORKFLOWSTEPNAME: item.WORKFLOWSTEPNAME,
                WORKFLOWID: item.WORKFLOWID,
                WORKFLOWNAME: item.WORKFLOWNAME,
                WORKFLOWREVISION: item.WORKFLOWREVISION,
                WORKFLOWINFO: item.WORKFLOWINFO,
                REALSTARTDATE: item.REALSTARTDATE,
                MFGSTARTDDATE: item.MFGSTARTDDATE,
                MFGENDDDATE: item.MFGENDDDATE
            };

            if (apsData != null) {
                var _containerAps = apsData.find(function (i) {
                    return i.CONTAINERID == item.CONTAINERID
                });
                if (_containerAps != null) {
                    _item.STARTTIME = _containerAps.STARTTIME;
                    _item.ENDTIME = _containerAps.ENDTIME;
                    _item.APSPLANINFOID = _containerAps.APSPLANINFOID;
                }
            }

            result.push(_item);
        });
        return result;
    },
    //查询批次级排产信息
    searchContainerAps: function () {
        //console.log(rowDatas);
        var rowDatas = $("#gdContainerInfo").datagrid("getChecked");
        if (rowDatas.length == 0) {
            return;
        }
        var containerPara = [];
        rowDatas.forEach(
          function (item) {
              containerPara.push({
                  containerId: item.CONTAINERID,
                  workflowId: item.WORKFLOWID
              });
          }
        );

        var param = {
            action: "getContainerInfiniteAps",
            containerPara: JSON.stringify(containerPara)
        };

        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ApsHandler/ApsInfiniteCapacity.ashx",
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $('#gdPositiveInfo').datagrid('loading');
                $('#gdReverseInfo').datagrid('loading');
            },
            success: function (data) {
                //console.log(data);
                $('#gdPositiveInfo').datagrid('loaded');
                $('#gdReverseInfo').datagrid('loaded');

                var result = JSON.parse(data);
                if (result.Result) {
                    var returnData = result.ReturnData;

                    //正排信息                    
                    var positiveData = page.generateInfiniteApsData(rowDatas, returnData.positiveInfo);
                    //倒排信息
                    var reverseData = page.generateInfiniteApsData(rowDatas, returnData.reverseInfo);

                    //console.log(positiveData);
                    $("#gdPositiveInfo").datagrid('loadData', { total: positiveData.length, rows: positiveData });
                    $("#gdPositiveInfo").datagrid('checkAll');
                    $("#gdReverseInfo").datagrid('loadData', { total: reverseData.length, rows: reverseData });
                    $("#gdReverseInfo").datagrid('checkAll');


                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#gdPositiveInfo').datagrid('loaded');
                $('#gdReverseInfo').datagrid('loaded');

                alert(XMLHttpRequest.responseText);
            }
        });


    },
    //查询
    searchData: function () {
        page.reset(false, true, true);
        var gridID = "#gdContainerInfo";
        var param = {
            action: "searchData",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            containerName: $("#txtContainer").textbox('getValue'),
            mfgorderName: $("#txtMfgorderName").textbox('getValue'),
            productName: $("#txtProduct").textbox('getValue'),
            factoryId: $("#factoryID").combobox('getValue'),
            orderStartDate: $("#txtOrderStartDate").datebox('getValue'),
            orderEndDate: $("#txtOrderEndDate").datebox('getValue')
        };
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ApsHandler/ApsInfiniteCapacity.ashx",
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //添加排产池
    addApsPool: function () {
        var url = "ApsLMContainerSelect.html?v=" + new Date().getTime();
        url += "&parentDiv=dg";

        $('#dg').dialog({
            title: '选择批次到排产池',
            fit: true,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            returnData: null,
            popupData: '', //弹出页面的传参
            onClose: function () {
                var returnData = $("#dg").dialog('options').returnData; //返回数据
                if (returnData != null) {
                    //console.log('更新父级数据');
                    page.searchData();
                    displayMessage("添加成功", true);
                }


            }
        });
    },
    //移除排产池
    removeApsPool: function () {
        var selectData = $('#gdContainerInfo').datagrid('getChecked');
        if (selectData.length == 0) {
            displayMessage("请选择数据", false);
            return;
        }
        var gridID = "#gdContainerInfo";
        var param = {
            action: "removeApsPool",
            containers: JSON.stringify(selectData)
        };
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ApsHandler/ApsLimitedCapacityHandler.ashx",
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    page.searchData();
                    displayMessage("移出成功", true);
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //清除方法，重要！！！
    reset: function (iscondition, isresult, isDetail) {
        clearMessage();
        if (iscondition) {
            $('#txtMfgorderName').textbox('clear');
            $('#txtProduct').textbox('clear');
            $('#txtContainer').textbox('clear');
            $('#txtOrderStartDate').datebox('clear');
            $('#txtOrderEndDate').datebox('clear');
        }
        if (isresult) {
            clearEasyuiDataGrid("gdContainerInfo", 1);
        }
        if (isDetail) {
            clearEasyuiDataGrid("gdPositiveInfo", 1);
            clearEasyuiDataGrid("gdReverseInfo", 1);
        }
    }
    //查看甘特图
    , viewGanttAndSave: function (data) {
        var param = JSON.parse(data);

        var url = "ApsInfiniteCapacityViewPage.html?v=" + new Date().getTime();
        url += "&parentDiv=dg";
        $('#dg').dialog({
            title: '批次工序计划甘特图',
            fit: true,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            popupData: param, //弹出页面的传参
            onClose: function () {
                page.searchContainerAps();
            }
        });
    }
}
$(function () {
    page.init();
});